<template>
  <t-dialog
    :width="width ? width : '60%'"
    :visible="showDialog"
    @confirm="handleConfirm"
    @close="handleCancel"
    @cancel="handleCancel"
    preventScrollThrough
    placement="center"
  >
    <template #header>{{ mode == "new" ? "新增" : mode == "edit" ? "编辑" : mode == "view" ? "查看" : "" }} </template>
    <t-form ref="formInstance" :data="pageData.formData" :rules="pageData.formRules" :disabled="pageData.readOnly">
      <t-form-item label="联系人姓名" name="name">
        <t-input :showLimitNumber="true" v-model="pageData.formData.name" maxlength="20" />
      </t-form-item>
      <t-form-item label="联系人手机" name="phone">
        <t-input :showLimitNumber="true" v-model="pageData.formData.phone" maxlength="100" />
      </t-form-item>
      <t-form-item label="联系人部门" name="department">
        <t-input :showLimitNumber="true" v-model="pageData.formData.department" maxlength="50" />
      </t-form-item>
      <t-form-item label="联系人职务" name="job">
        <t-input :showLimitNumber="true" v-model="pageData.formData.job" maxlength="50" />
      </t-form-item>
      <t-form-item label="微信号" name="wechatId">
        <t-input :showLimitNumber="true" v-model="pageData.formData.wechatId" maxlength="50" />
      </t-form-item>
      <t-form-item label="WhatsApp" name="whatsAppId">
        <t-input :showLimitNumber="true" v-model="pageData.formData.whatsappId" maxlength="50" />
      </t-form-item>
    </t-form>
  </t-dialog>
</template>

<script lang="tsx" setup>
// 框架和组件库
import { reactive, ref, toRaw } from "vue";
import type { FormInstanceFunctions, FormRule } from "tdesign-vue-next";

const props = defineProps(["width", "showDialog", "mode", "editFormData"]);
const emits = defineEmits(["onCancel", "onConfirm"]);

const formInstance = ref<FormInstanceFunctions | null>(null);

const pageData = reactive<Record<string, any>>({
  readOnly: false,
  formData: {
    id: "",
    localUUID: "",
    status: 0,
    hasDeleted: 0,
    remark: "",
    name: "",
    phone: "",
    department: "",
    wechatId: "",
    whatsappId: "",
    job: ""
  },
  formRules: {
    name: [{ required: true, message: "请输入姓名", type: "error", trigger: "blur" }],
    phone: [
      { required: true, message: "请输入电话", type: "error", trigger: "blur" },
      { telnumber: true, message: "请输入正确的手机号码" }
    ]
  } as FormRule
});
const handleCancel = () => {
  emits("onCancel");
};

const handleConfirm = async () => {
  const validateResult = await formInstance?.value?.validate();
  if (validateResult === true) {
    emits("onConfirm", toRaw(pageData.formData));
  }
};

if (props.editFormData) {
  pageData.formData = toRaw(props.editFormData);
}
</script>
